package comm

import (
	"database/sql"
	"errors"
	"fmt"
	"log"

	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"

	"main/model"
)

// ORM engine
var x *xorm.Engine

func DBPrepare(dbname string) {
	db, err := sql.Open("mysql", "root:Letmein123@tcp(localhost:43306)/?charset=utf8")
	if err != nil {
		panic(err)
	}
	defer db.Close()

	_, err = db.Exec("CREATE DATABASE IF NOT EXISTS " + dbname)
	if err != nil {
		panic(err)
	}
}

func DBSync(dbname string) {
	// Create ORM engine and database
	var err error
	addr := fmt.Sprintf("root:Letmein123@tcp(localhost:43306)/%s?charset=utf8", dbname)
	x, err = xorm.NewEngine("mysql", addr)
	if err != nil {
		log.Fatalf("Fail to create engine: %v\n", err)
	}

	//x.ShowSQL(true)
	// Sync tables
	if err = x.Sync(new(model.Account)); err != nil {
		log.Fatalf("Fail to sync database: %v\n", err)
	}
}

func TestDataInit() {
	NewAccount(&model.Account{Name: "allen", Balance: 1000})
	NewAccount(&model.Account{Name: "dobe", Balance: 2000})
}

func NewAccount(a *model.Account) error {
	_, err := x.Insert(a)
	return err
}

func GetAccount(id int64) (*model.Account, error) {
	a := &model.Account{}
	has, err := x.Id(id).Get(a)
	if err != nil {
		return nil, err
	} else if !has {
		return nil, errors.New("Account does not exist")
	}
	return a, nil
}

func UpdateAccount(a *model.Account) error {
	_, err := x.Id(a.Id).Update(a)
	return err
}

func GetAccountsAscId() (as []model.Account, err error) {
	err = x.Find(&as)
	return as, err
}

func GetAccountsDescBalance() (as []model.Account, err error) {
	err = x.Desc("balance").Find(&as)
	return as, err
}

func DeleteAccount(id int64) error {
	_, err := x.Delete(&model.Account{Id: id})
	return err
}
